package com.wisdomech.server.service;


import com.wisdomech.server.entity.CardInfo;
import com.wisdomech.server.entity.UrlList;
import com.wisdomech.server.respository.CardInfoRepository;
import com.wisdomech.server.respository.UrllistRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import javax.annotation.PostConstruct;
import java.util.List;


/**
 * @Author: tubashu
 * @Date: 2018/8/9 23:35
 * @email: tubashu@mail.ru
 */

@Component
public class CardPipeline implements Pipeline {

    @Autowired
    private UrllistRepository urllistRepository;

    @Autowired
    private CardInfoRepository cardInfoRepository;

    private static CardPipeline cardPipeline;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        cardPipeline = this;
        cardPipeline.urllistRepository = this.urllistRepository;
        cardPipeline.cardInfoRepository = this.cardInfoRepository;
        // 初使化时将已静态化的testService实例化
    }

    @Override
    public void process(ResultItems resultItems, Task task) {

        List<String> urls = resultItems.get("link");
        List<String> imgs = resultItems.get("imgs");
        if (urls != null) {
            for (int i = 0; i < urls.size(); i++) {
                String url = urls.get(i);
                String img = imgs.get(i);
                if (url != null) {
                    UrlList u = cardPipeline.urllistRepository.findByUrl(url);
                    if (u == null) {
                        UrlList urlList = new UrlList();
                        urlList.setUrl(url);
                        urlList.setImg(img);
                        if (cardPipeline.urllistRepository == null) {
                            System.out.print("装载失败\n");
                            System.exit(0);
                        }
                        cardPipeline.urllistRepository.save(urlList);
                    }
                }
            }
        }
        CardInfo cardInfo = resultItems.get("info");
        if (cardInfo != null) {
            cardPipeline.cardInfoRepository.save(cardInfo);
        }

    }

}